/*
 * @Author: jiu yin
 * @Date: 2024-12-31 18:15:08
 * @LastEditTime: 2025-01-15 18:34:43
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \node-socket-sersvice\src\webSocket\message.js
 */
const path = require("path");
const { device_online, web_ws } = require("./store");
let { downloadFile } = require("../utils/download");
const logger = require("../service.js");
const type_web = "web";
const type_xr = "xr";

function message(ws, clientIP, data) {
	if (data.type == type_web) {
		if (!web_ws.has(clientIP)) {
			web_ws.set(clientIP, ws);
			logger.info(
				"存储web端",
				[...web_ws.keys()].length,
				[...web_ws.keys()].map(item => ({ clientIP: item }))
			);
		}
		actions_web[data.action] && actions_web[data.action](ws, clientIP, data);
	} else if (data.type == type_xr) {
		actions_xr[data.action] && actions_xr[data.action](ws, clientIP, data);
	}
}
let actions_web = {
	//获取在线设备
	"/api/query/list": (ws, clientIP, data) => {
		let arr = device_online.map(item => ({ sn: item.sn, time: item.time, clientIP: item.clientIP }));
		successSend({ ws, action: "/api/query/list", type: "web", payload: { list: arr } });
	},
	//安装apk和zip地图
	"/app/upgrade": async (ws, clientIP, data) => {
		if (data.payload.range && data.payload.url) {
			let arr = data.payload.range.split(",");
			let arr_online = arr.map(sn => {
				let find = device_online.find(i => i.sn == sn);
				if (!find) {
					ErrorSend({ ws, action: "/app/upgrade", type: "web", payload: { ...data.payload, sn }, code: 505 });
					return null;
				}
				return find;
			});
			arr_online = arr_online.filter(item => item);
			if (!arr_online.length) return;
			try {
				arr_online.forEach(item => {
					successSend({
						ws,
						action: "/app/upgrade",
						type: "web",
						payload: { ...data.payload, sn: item.sn, status: "downStart" },
					});
				});
				let url = await downloadFile(data.payload.url, path.basename(new URL(data.payload.url).pathname));
				arr_online.forEach(item =>
					successSend({ ws: item.ws, action: "/app/upgrade", type: "xr", payload: { ...data.payload, sn: item.sn, url } })
				);
			} catch (err) {
				logger.info("[ err ] >", err);
				arr_online.forEach(item => {
					ErrorSend({
						ws: ws,
						action: "/app/upgrade",
						type: "web",
						payload: { ...data.payload, sn: item.sn, status: "error" },
						code: 500,
						message: "下载失败",
					});
				});
			}
		} else {
			ErrorSend({ ws: ws, action: "/app/upgrade", type: "web", payload: data.payload, code: 500, message: "参数错误" });
		}
	},
	//获取电量
	"/api/device/battery": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/battery", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/battery", type: "xr", payload: data.payload });
	},
	//获取左右手手电量
	"/api/device/battery/controller": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/battery/controller", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/battery/controller", type: "xr", payload: data.payload });
	},
	//关机
	"/api/device/shutdown": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/shutdown", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/shutdown", type: "xr", payload: data.payload });
	},
	//重启
	"/api/device/restart": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/restart", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/restart", type: "xr", payload: data.payload });
	},
	//息屏/亮屏
	"/api/device/screen": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/screen", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/screen", type: "xr", payload: data.payload });
	},
	//设置音量
	"/api/device/volume": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/volume", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/volume", type: "xr", payload: data.payload });
	},
	//获取当前屏幕状态
	"/api/device/currentScreen": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/currentScreen", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/currentScreen", type: "xr", payload: data.payload });
	},
	//获取当前运行的app
	"/api/device/currentPackage": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/currentPackage", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/currentPackage", type: "xr", payload: data.payload });
	},
	//启动停止APP
	"/api/device/app/launch": (ws, clientIP, data) => {
		let item = device_online.find(item => data.payload.sn == item.sn);
		if (!item) {
			return ErrorSend({ ws, action: "/api/device/app/launch", type: "web", payload: data.payload, code: 505 });
		}
		successSend({ ws: item.ws, action: "/api/device/app/launch", type: "xr", payload: data.payload });
	},
};

let actions_xr = {
	//存储在线设备
	"/device_online": (ws, clientIP, data) => {
		let index = device_online.findIndex(item => item.sn == data.payload.sn);
		if (index == -1) {
			device_online.push({ ...data.payload, time: new Date().toLocaleString("zh-CN"), ws, clientIP });
			logger.info(
				"存储在线设备",
				device_online.length,
				device_online.map(item => ({ clientIP: item.clientIP, sn: item.sn }))
			);
		}
	},
	// 广播给web  app升级状态
	"/app/upgrade": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/app/upgrade", type: "web", payload: data.payload });
		});
	},
	//获取电量
	"/api/device/battery": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/battery", type: "web", payload: data.payload });
		});
	},
	//获取左右手手电量
	"/api/device/battery/controller": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/battery/controller", type: "web", payload: data.payload });
		});
	},
	//关机
	"/api/device/shutdown": (ws, clientIP, data) => {
		if (data.payload.status == 1) ws.terminate();
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/shutdown", type: "web", payload: data.payload });
		});
	},
	//重启
	"/api/device/restart": (ws, clientIP, data) => {
		if (data.payload.status == 1) ws.terminate();
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/restart", type: "web", payload: data.payload });
		});
		ws.terminate();
	},
	//息屏/亮屏
	"/api/device/screen": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/screen", type: "web", payload: data.payload });
		});
	},
	//设置音量
	"/api/device/volume": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/volume", type: "web", payload: data.payload });
		});
	},
	//获取当前屏幕状态
	"/api/device/currentScreen": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/currentScreen", type: "web", payload: data.payload });
		});
	},
	//获取当前运行的app
	"/api/device/currentPackage": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/currentPackage", type: "web", payload: data.payload });
		});
	},
	//启动停止APP
	"/api/device/app/launch": (ws, clientIP, data) => {
		web_ws.forEach(item => {
			successSend({ ws: item, action: "/api/device/app/launch", type: "web", payload: data.payload });
		});
	},
};

function successSend({ ws, action, payload, type }) {
	let data = JSON.stringify({ type, action, payload, code: 200 });
	ws.send(data);
	logger.info("[发送成功消息  ] >", data);
}

function ErrorSend({ ws, action, payload, type, code, message }) {
	let codeObj = {
		505: "设备不在线",
	};
	let data = JSON.stringify({ type, action, payload, code, message: message || codeObj[code] });
	ws.send(data);
	logger.info("[发送失败消息   ] >", data);
}

module.exports = { message, successSend, ErrorSend };
